#include "drawing.h"
#include "mypushbutton.h"
#include <QGraphicsLineItem>
#include <QTimer>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include<QApplication>
#include<QPushButton>
#include<exception>
#include <QFileDialog>


DrawingScene::DrawingScene(QObject *parent)
    : QGraphicsScene(parent),m_view(nullptr)
{
    //设置绘画和擦除操作的初始值
    m_isErasing = false;
    m_isDrawing = false;


}

void DrawingScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_isDrawing = true;
        m_lastPos = event->scenePos();

    } else if (event->button() == Qt::RightButton) {
        m_isErasing = true;
    }
}

void DrawingScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_isErasing) {
        // 清除轨迹上的图像
        QList<QGraphicsItem*> items = this->items(QRectF(event->scenePos() - QPointF(5, 5), QSizeF(20, 20)));
        for (QGraphicsItem *item : items) {
            if (item->type() == QGraphicsLineItem::Type) {
                removeItem(item);
                delete item;
            }
        }
    } else if (m_isDrawing) {

        // 绘制曲线
        QGraphicsLineItem *line = new QGraphicsLineItem();
        line->setPen(QPen(Qt::black, 5)); // 使用当前画笔颜色和宽度
        line->setLine(QLineF(m_lastPos, event->scenePos()));
        addItem(line);
        m_lastPos = event->scenePos();
        // 将当前图形项添加到当前操作中
        QList<QGraphicsItem*> itemsToAdd;
        itemsToAdd.append(line);
        m_currentOperation.append(itemsToAdd);
        // 发出信号表明场景已更改
        emit drawingchanged();
    }
}


void DrawingScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::RightButton) {
        m_isErasing = false;
    } else if (event->button() == Qt::LeftButton) {

        m_isDrawing = false;

    }
}





